package myJs.implicits

import scala.scalajs.js
import scala.scalajs.js.{URIUtils}
import myJs.Implicits._

import scala.util.Try
import upickle.default._

/** Created by Administrator on 2020/1/16
  */
trait MyStringTool {

  type JArJDJAn = js.Array[js.Dictionary[js.Any]]
  type JArJAn = js.Array[js.Any]
  type JArJDS = js.Array[js.Dictionary[String]]
  type JDJAn = js.Dictionary[js.Any]
  type JDS = js.Dictionary[String]
  type JArS = js.Array[String]

  implicit class MyString(v: String) {

    def toObj = {
      read[ujson.Obj](v)
    }

    def toArr = {
      read[ujson.Arr](v)
    }

    def headLower = {
      if (v == null || v.length == 0 || !v.charAt(0).isUpper) v
      else v.updated(0, v.charAt(0).toLower)
    }

    def nonBlank = {
      v.trim.nonEmpty
    }

    def isBlank = {
      !nonBlank
    }

    def toMyArray = {
      if (v.isEmpty) {
        js.Array[String]()
      } else js.Array(v)
    }

    def isDouble: Boolean = {
      Try(v.toDouble).toOption match {
        case Some(value) => true
        case None => false
      }
    }

    def px2Int = {
      v.replaceAll("px$", "").toInt
    }

    def px2Double = {
      v.replaceAll("px$", "").toDouble
    }

    def encodeURI = {
      URIUtils.encodeURIComponent(v)
    }

    def null2Empty = {
      if (v == null) "" else v
    }
    def onlyDoubleFixed(n: Int) = {
      if (v.isDouble) {
        v.toDouble.toFixed(n)
      } else v
    }

  }

}
